package pt.compflow.graph;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Tree implements Iterable<Tree> {

	private String node;
	private Tree parent;
	private List<Tree> children;

	public Tree() {
		children = new ArrayList<Tree>();
	}

	public Tree(String node, Tree parent) {
		this();
		this.node = node;
		this.parent = parent;
		if (parent != null)
			parent.addChildren(this);
	}

	public void addChildren(Tree tree) {
		if (!children.contains(tree))
			children.add(tree);
	}

	public void removeChildren(Tree tree) {
		children.remove(tree);
	}

	public void addChildren(String node) {
		new Tree(node, this);
	}

	public boolean isEmpty() {
		if (node != null)
			return false;
		if (children.size() <= 0)
			return true;

		for (Tree tree : children)
			if (!tree.isEmpty())
				return false;

		return true;
	}

	public String getNode() {
		return node;
	}

	public void setNode(String node) {
		this.node = node;
	}

	public Tree getParent() {
		return parent;
	}

	public void setParent(Tree parent) {
		this.parent = parent;
	}

	public List<Tree> getChildren() {
		return children;
	}

	@Override
	public Iterator<Tree> iterator() {
		return new TreeIterator(this);
	}
	
	@Override
	public String toString() {
		Iterator<Tree> it = iterator();
		StringBuilder builder = new StringBuilder();
		builder.append("[");
		while(it.hasNext()) {
			builder.append(it.next().getNode());
			if(it.hasNext()) builder.append(", ");
		}
		builder.append("]");
		return builder.toString();
	}
}
